package com.example.star.view.setting;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.star.R;
import com.example.star.api_service.ApiFeedback;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FeedbackActivity extends AppCompatActivity {

    private String currentUserName;
    private boolean isAdmin;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 从 SharedPreferences 读取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        currentUserName = sharedPreferences.getString("username", "");

        // 显示加载对话框
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在检查用户角色...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        checkUserRoleFromServer();
    }

    private void checkUserRoleFromServer() {
        ApiFeedback apiFeedback = ApiClient.getApiFeedback();
        Call<User> call = apiFeedback.getUserByUsername(currentUserName);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                // 隐藏加载对话框
                progressDialog.dismiss();
                if (response.isSuccessful()) {
                    User user = response.body();
                    if (user != null) {
                        isAdmin = user.isAdmin();
                        // 直接根据角色跳转
                        jumpAccordingToRole();
                    }
                } else {
                    Log.e("User", "获取用户信息失败: " + response.message());
                    Toast.makeText(FeedbackActivity.this, "获取用户信息失败，请稍后重试", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                // 隐藏加载对话框
                progressDialog.dismiss();
                Log.e("User", "网络请求失败: " + t.getMessage());
                Toast.makeText(FeedbackActivity.this, "网络请求失败，请稍后重试", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    private void jumpAccordingToRole() {
        Intent intent;
        if (isAdmin) {
            // 管理员用户，启动发送回复页面
            intent = new Intent(FeedbackActivity.this, SendReplyActivity.class);
        } else {
            // 普通用户，启动发送反馈页面
            intent = new Intent(FeedbackActivity.this, SendFeedbackActivity.class);
        }
        startActivity(intent);
        finish(); // 关闭当前 Activity
    }
}